package priv.bestbeat.reportcenter.core.mq.rocket.example;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.util.List;

/**
 * @author 张渠钦
 * @date 2022/4/18 11:25
 */
public class OrderedProducer {

    public static void main(String[] args) throws Exception {
        MQProducer producer = new DefaultMQProducer("g4");

        producer.start();

        String[] tags = new String[]{"tagA","tagB","tagC","tagD","tagE"};
        for (int i = 0; i < 100; i++) {
            int orderId = i % 10;
            Message msg = new Message("topic5",tags[ i % tags.length],"KEY" + i,("Hello RockerMQ" + i).getBytes(RemotingHelper.DEFAULT_CHARSET) );
            SendResult sendResult = producer.send(msg, new MessageQueueSelector() {
                @Override
                public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                    Integer id = (Integer) arg;
                    int index = id % mqs.size();
                    return mqs.get(index);
                }
            },orderId);

            System.out.printf("%s%n", sendResult);
        }

        producer.shutdown();
    }

}
